package com.cskaoyan.service.userservice;

import com.cskaoyan.bean.userbean.Address;
import com.cskaoyan.bean.userbean.AddressExample;
import com.cskaoyan.mapper.mallmapper.RegionMapper;
import com.cskaoyan.mapper.usermapper.AddressMapper;
import com.cskaoyan.vo.uservo.AddressListVo;
import com.cskaoyan.vo.uservo.AddressVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hsp
 * @date 2021/5/11 12:11
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    RegionMapper regionMapper;
    @Override
    public AddressListVo addressList(Integer page, Integer limit, String name, Integer userId, String sort, String order) {
        PageHelper.startPage(page,limit);
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        if (name!=null)
            criteria.andNameLike("%"+name+"%");
        if (userId!=null)
            criteria.andUserIdEqualTo(userId);
        addressExample.setOrderByClause(sort + " "+ order);//order by add_time descc
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        PageInfo<Address> addressPageInfo = new PageInfo<>(addresses);
        int total = addressPageInfo.getSize();

        List<AddressVo> addressVos = new ArrayList<>();
        for (Address address : addresses) {
            AddressVo tempAddressVo = new AddressVo(
                regionMapper.selectRegionNameById(address.getAreaId()),
                    address.getIsDefault(),
                    address.getAreaId(),
                    address.getAddress(),
                    regionMapper.selectRegionNameById(address.getProvinceId()),
                    regionMapper.selectRegionNameById(address.getCityId()),
                    address.getName(),
                    address.getMobile(),
                    address.getId(),
                    address.getCityId(),
                    address.getUserId(),
                    address.getProvinceId()
            );
            addressVos.add(tempAddressVo);

        }
        AddressListVo addressListVo = new AddressListVo();
        addressListVo.setItems(addressVos);
        addressListVo.setTotal(total);
        return addressListVo;
    }
}
